﻿#include "http_client.h"

//网络客户端网络请求响应
void HttpClient::OnHttpEvent(mg_connection *connection, int event_type, void *event_data)
{
	http_message *hm = (struct http_message *)event_data;
	int connect_status;

	switch (event_type) 
	{
	case MG_EV_CONNECT:
		connect_status = *(int *)event_data;
		if (connect_status != 0) 
		{
			printf("Error connecting to server, error code: %d\n", connect_status);
			*(int*)connection->mgr->user_data = 1;			
		}
		else {
			printf("connect_status: %d\n", connect_status);
		}
		break;
	case MG_EV_HTTP_REPLY:
	{
		//printf("Got reply:\n%.*s\n", (int)hm->body.len, hm->body.p);
		std::string rsp = std::string(hm->body.p, hm->body.len);
		connection->flags |= MG_F_SEND_AND_CLOSE;		
        *(int*)connection->mgr->user_data = 1;
		on_http_response(rsp);
	}
		break;
	case MG_EV_CLOSE:
		if (*(int*)connection->mgr->user_data == 0) 
		{
			printf("Server closed connection\n");			
			*(int*)connection->mgr->user_data = 1;
		};
		break;
	default:
		break;
	}
}

void HttpClient::on_http_response(const string res)
{
	printf("http res: %s\n", res.c_str());
}

//发送一次请求，并回调处理,然后关闭本次连接
void HttpClient::SendReq(const std::string &url)
{	
	mg_mgr mgr;
	int exit_flag = 0;
	mg_mgr_init(&mgr, &exit_flag);
	auto connection = mg_connect_http(&mgr, OnHttpEvent, url.c_str(), NULL, NULL);
	mg_set_protocol_http_websocket(connection);

	//printf("Send http request %s s_exit_flat: %d\n", url.c_str(), exit_flag);		
	while (exit_flag == 0) {
		mg_mgr_poll(&mgr, 500);
	}
		
	mg_mgr_free(&mgr);
}